package org.liaohailong.library.util

import android.graphics.Bitmap
import android.graphics.Color

import com.google.zxing.BarcodeFormat
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter

/**
 * Author: liaohailong
 * Date: 2019/3/19
 * Time: 8:13 PM
 * Description: 二维码生成工具（去白边）
 */
object QRCodeUtil {

    fun createQRCode(str: String, width: Int, height: Int): Bitmap? {
        val matrixWidth: Int
        val matrixHeight: Int
        try {
            var matrix = QRCodeWriter().encode(str, BarcodeFormat.QR_CODE, width, height)
            matrix = reduceWhite(matrix, 10) // 删除白边
            matrixWidth = matrix.width
            matrixHeight = matrix.height
            val pixels = IntArray(matrixWidth * matrixHeight)
            for (y in 0 until matrixHeight) {
                for (x in 0 until matrixWidth) {
                    if (matrix.get(x, y)) {
                        pixels[y * matrixWidth + x] = Color.BLACK
                    } else {
                        pixels[y * matrixWidth + x] = Color.WHITE
                    }
                }
            }
            val bitmap = Bitmap.createBitmap(matrixWidth, matrixHeight, Bitmap.Config.ARGB_8888)
            bitmap.setPixels(pixels, 0, matrixWidth, 0, 0, matrixWidth, matrixHeight)
            return bitmap
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 缩小生成二维码白边框(删除白边 重新添加新白边)
     *
     * @param matrix
     * @return
     */
    private fun reduceWhite(matrix: BitMatrix, margin: Int): BitMatrix {
        val tempM = margin * 2
        val rec = matrix.enclosingRectangle // 获取二维码图案的属性
        val resWidth = rec[2] + tempM
        val resHeight = rec[3] + tempM
        val resMatrix = BitMatrix(resWidth, resHeight) // 按照自定义边框生成新的BitMatrix
        resMatrix.clear()
        for (i in margin until resWidth - margin) { // 循环，将二维码图案绘制到新的bitMatrix中
            for (j in margin until resHeight - margin) {
                if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {
                    resMatrix.set(i, j)
                }
            }
        }
        return resMatrix
    }
}
